package com.ucode.hrm.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.hrm.service.HrmPersonalResumeService;
import com.ucode.model.hrm.HrmPersonalResume;
import com.ucode.model.hrm.convert.HrmPersonalResumeConvert;
import com.ucode.model.hrm.form.HrmPersonalResumeForm;
import com.ucode.model.hrm.form.HrmPersonalResumeHandleForm;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.util.IdentifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "管理后台 - 人力资源系统 - 个人简历")
@RestController
@RequestMapping("/hrm/personal-resume")
@Validated
public class HrmPersonalResumeController {

    @Resource
    private HrmPersonalResumeService personalResumeService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:query')")
    public ResponseResult<Paginator<HrmPersonalResume>> pageList(
            @Schema(description = "姓名") @RequestParam(value = "name",required = false) String name,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "邮箱") @RequestParam(value = "email",required = false) String email,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "学历") @RequestParam(value = "education",required = false) Integer education,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(name))
            condition.put("name", StrUtil.concat(true,"%", name,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(StrUtil.isNotBlank(email))
            condition.put("email", StrUtil.concat(true,"%", email,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("gender",gender);
        condition.put("education",education);
        condition.put("deltag",false);

        Paginator<HrmPersonalResume> paginator = personalResumeService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @GetMapping("/job-post/page-list")
    @Operation(summary = "获得岗位应聘简历分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:query')")
    public ResponseResult<Paginator<HrmPersonalResume>> pageListByJobPost(
            @Schema(description = "岗位编号") @RequestParam(value = "jobPostId",required = true) Long jobPostId,
            @Schema(description = "姓名") @RequestParam(value = "name",required = false) String name,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "邮箱") @RequestParam(value = "email",required = false) String email,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "学历") @RequestParam(value = "education",required = false) Integer education,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(name))
            condition.put("name", StrUtil.concat(true,"%", name,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(StrUtil.isNotBlank(email))
            condition.put("email", StrUtil.concat(true,"%", email,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }

        condition.put("jobPostId",jobPostId);
        condition.put("gender",gender);
        condition.put("education",education);
        condition.put("deltag",false);

        Paginator<HrmPersonalResume> paginator = personalResumeService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @GetMapping("/list-simple-page")
    @Operation(summary = "分页获取精简信息列表(没有权限校验，公共查询接口)", description = "主要用于前端的下拉选项")
    public ResponseResult<Paginator<HrmPersonalResume>> simplePageList(
            @Schema(description = "姓名") @RequestParam(value = "name",required = false) String name,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "邮箱") @RequestParam(value = "email",required = false) String email,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "学历") @RequestParam(value = "education",required = false) Integer education,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(name))
            condition.put("name", StrUtil.concat(true,"%", name,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(StrUtil.isNotBlank(email))
            condition.put("email", StrUtil.concat(true,"%", email,"%"));

        condition.put("gender",gender);
        condition.put("education",education);
        condition.put("deltag",false);

        Paginator<HrmPersonalResume> paginator = personalResumeService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:query')")
    public ResponseResult<HrmPersonalResume> getById(@PathVariable(name="id",required=true) Long id){
        HrmPersonalResume bean = personalResumeService.validate(id);
        return ResponseResult.success(bean);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:create')")
    public ResponseResult<Long> create(@Valid @RequestBody HrmPersonalResumeForm form) {
        HrmPersonalResume bean = HrmPersonalResumeConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        if(ObjUtil.isNotNull(bean.getBirthDate())) {
            bean.setAge(DateUtil.ageOfNow(LocalDateTimeUtil.format(bean.getBirthDate(), DatePattern.NORM_DATE_PATTERN)));
        }
        Long id = personalResumeService.insert(bean);
        return id != null ? ResponseResult.success(id) : ResponseResult.failed();
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody HrmPersonalResumeForm form) {
        HrmPersonalResume bean = HrmPersonalResumeConvert.INSTANCE.convert(form);
        bean.setId(id);
        if(ObjUtil.isNotNull(bean.getBirthDate())) {
            bean.setAge(DateUtil.ageOfNow(LocalDateTimeUtil.format(bean.getBirthDate(), DatePattern.NORM_DATE_PATTERN)));
        }

        int i = personalResumeService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/update-status")
    @Operation(summary = "更新状态")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:update-status')")
    public ResponseResult<Long> create(@Valid @RequestBody HrmPersonalResumeHandleForm form) {
        HrmPersonalResume bean = new HrmPersonalResume();
        bean.setId(form.getId());
        bean.setApplyStatus(form.getApplyStatus());
        bean.setApplyRemark(form.getApplyRemark());
        int i = personalResumeService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = personalResumeService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('hrm:personal-resume:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = personalResumeService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

}
